import * as express from 'express';
import * as glob from 'glob';
import * as path from 'path';
import { V } from "x-engine";
import { X } from "x-orm";

import * as http from 'http';
import * as nunjucks from 'nunjucks';
import * as bodyParser from 'body-parser';
import { ORMCONFIG, DEBUG_MODE } from './config';
import { date, strtotime } from 'locutus/php/datetime';
var cookieSession = require('cookie-session')

declare var FuseBox;

export class Bootstrap {
    static async start() {
        var loadMain = function () {
            return new Promise(function (resolve, reject) {
                var callback =
                    typeof FuseBox == 'undefined' ?
                        function () {
                            glob(path.resolve(__dirname, 'app/*/main.js'), function (err, files) {
                                console.log(files)
                                files.forEach(file => {
                                    require(file);
                                })
                                resolve('ok');
                            });
                        } :
                        function () {
                            require('~/app/*/main.js');
                            resolve('ok');
                        };
                callback();
            })
        };

        await loadMain();

        //注册控制器
        const app = express();
        const server = http.createServer(app);
        const inFuseBox = typeof FuseBox !== 'undefined'

        app.use("/static/", express.static(path.resolve(__dirname, inFuseBox ? "static" : "../static")));

        app.use(bodyParser.urlencoded({ extended: false }));

        app.use(cookieSession({
            secret: "1q2w3e4r",
            // cookie: {maxAge: 60 * 1000 * 300} 
            maxAge: 24 * 60 * 60 * 1000
        }))
        var env = nunjucks.configure(path.resolve(__dirname, inFuseBox ? 'views' : '../views'), {
            autoescape: true,
            express: app,
            noCache: DEBUG_MODE
        });

        // env.addFilter('money', function (value) {
        //     return toDecimal2(value);
        // });
        env.addFilter('sdate', function (value) {
            return date("Y-m-d", value);
        });
        env.addFilter('fdate', function (value) {
            return date("Y-m-d H:i:s", value);
        });

        env.addFilter("mdate",function(value : Date | string){
            if(value && typeof value == 'object'){
                value = value as Date;
                return value.getFullYear() + '-' + (value.getMonth() + 1) + '-' + value.getDate();
            }
            return value ? (value as string).substr(0,10) : '';
        });

        env.addFilter("money",function(value){
            var f = parseFloat(value);
            if (isNaN(f)) {
                return false;
            }
            var f = Math.round(value * 100) / 100;
            var s = f.toString();
            var rs = s.indexOf('.');
            if (rs < 0) {
                rs = s.length;
                s += '.';
            }
            while (s.length <= rs + 2) {
                s += '0';
            }
            return s;
        });

        V.startExpressServer({
            app: app,
            crossDomain: true
        });

        //注册orm
        X.startORM(ORMCONFIG).then(() => {
            //开启采集线程
            // const collect = new Collect;
            // collect.collect("2017-09-28");
        });
        

        server.listen(8015);

        console.log("启动成功！");
    }
}